<template>
  <div class="pokemon-page">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1 class="page-title">宝可梦图鉴</h1>
      <p class="page-subtitle">探索所有宝可梦的详细信息</p>
    </div>
    
    <!-- 搜索和筛选区域 -->
    <div class="search-filter-section">
      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-input
          v-model="searchQuery"
          placeholder="搜索宝可梦名称或编号..."
          size="large"
          clearable
          @input="handleSearch"
          @clear="handleSearch"
        >
          <template #prefix>
            <el-icon><Search /></el-icon>
          </template>
        </el-input>
        <el-button 
          type="primary" 
          size="large" 
          @click="handleSearch"
          :loading="loading"
        >
          搜索
        </el-button>
      </div>
      
      <!-- 筛选器 -->
      <div class="filters">
        <!-- 属性筛选 -->
        <div class="filter-group">
          <label class="filter-label">属性:</label>
          <el-select
            v-model="selectedType"
            placeholder="所有属性"
            size="large"
            clearable
            @change="handleFilter"
          >
            <el-option label="所有属性" value="" />
            <el-option
              v-for="type in pokemonTypes"
              :key="type"
              :label="type"
              :value="type"
            />
          </el-select>
        </div>
        
        <!-- 世代筛选 -->
        <div class="filter-group">
          <label class="filter-label">世代:</label>
          <el-select
            v-model="selectedGeneration"
            placeholder="所有世代"
            size="large"
            clearable
            @change="handleFilter"
          >
            <el-option label="所有世代" value="" />
            <el-option label="第一世代 (1-151)" value="1" />
            <el-option label="第二世代 (152-251)" value="2" />
            <el-option label="第三世代 (252-386)" value="3" />
          </el-select>
        </div>
        
        <!-- 排序方式 -->
        <div class="filter-group">
          <label class="filter-label">排序:</label>
          <el-select
            v-model="sortBy"
            size="large"
            @change="handleSort"
          >
            <el-option label="按编号排序" value="number" />
            <el-option label="按名称排序" value="name" />
          </el-select>
        </div>
      </div>
    </div>
    
    <!-- 结果统计 -->
    <div class="result-info" v-if="!loading">
      <span class="result-count">
        共找到 <strong>{{ totalCount }}</strong> 只宝可梦
      </span>
      <span class="current-showing" v-if="filteredPokemonList.length > 0">
        当前显示第 {{ (currentPage - 1) * pageSize + 1 }} - {{ Math.min(currentPage * pageSize, filteredPokemonList.length) }} 只
      </span>
    </div>
    
    <!-- 宝可梦卡片网格 -->
    <div class="pokemon-grid" v-loading="loading">
      <div 
        v-for="pokemon in paginatedPokemonList" 
        :key="pokemon.id"
        class="pokemon-card"
        @click="showPokemonDetail(pokemon)"
      >
        <div class="pokemon-number">#{{ getPokemonNumber(pokemon) }}</div>
        <div class="pokemon-image" :style="{ background: getPrimaryTypeGradient(pokemon) }">
          <img 
            :src="getPokemonImage(pokemon)" 
            :alt="getPokemonName(pokemon)"
            @error="handleImageError($event, pokemon)"
          >
        </div>
        <div class="pokemon-info">
          <div class="pokemon-bottom">
            <div class="pokemon-name-section">
              <h3 class="pokemon-name">{{ getPokemonName(pokemon) }}</h3>
            </div>
            <div class="pokemon-type-colors">
              <div 
                v-for="type in pokemon.types.slice(0, 2)" 
                :key="type.id"
                class="type-color-block"
                :style="{ 
                  backgroundColor: typeColors[type.typeName] || '#68d391',
                  height: pokemon.types.length === 1 ? '100%' : '50%'
                }"
                :title="type.typeName"
              ></div>
            </div>
          </div>
          <div class="pokemon-stats">
            <div class="stat-item">
              <span class="stat-label">身高:</span>
              <span class="stat-value">{{ pokemon.height || 'N/A' }}m</span>
            </div>
            <div class="stat-item">
              <span class="stat-label">体重:</span>
              <span class="stat-value">{{ pokemon.weight || 'N/A' }}kg</span>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 空状态 -->
    <div v-if="!loading && filteredPokemonList.length === 0" class="empty-state">
      <div class="empty-icon">🔍</div>
      <h3>未找到宝可梦</h3>
      <p>请尝试调整搜索条件或筛选器</p>
      <el-button @click="resetFilters" type="primary" class="reset-primary-btn">重置筛选</el-button>
    </div>
    
    <!-- 分页 -->
    <div class="pagination-section" v-if="filteredPokemonList.length > 0">
      <el-pagination
        :current-page="currentPage"
        :page-size="pageSize"
        :page-sizes="[12, 24, 48, 96]"
        :total="totalCount"
        layout="total, sizes, prev, pager, next, jumper"
        @current-change="handlePageChange"
        @size-change="handlePageSizeChange"
      />
    </div>
    
    <!-- 宝可梦详情对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="selectedPokemon?.pokemonName || '宝可梦详情'"
      width="600px"
      center
    >
      <div v-if="selectedPokemon" class="pokemon-detail">
        <div class="detail-header">
          <div class="detail-image">
            <img :src="getPokemonImage(selectedPokemon)" :alt="getPokemonName(selectedPokemon)">
          </div>
          <div class="detail-basic">
            <h2 class="detail-name">{{ getPokemonName(selectedPokemon) }}</h2>
            <div class="detail-number">#{{ getPokemonNumber(selectedPokemon) }}</div>
            <div class="detail-category">{{ selectedPokemon.category || '未知分类' }}</div>
            <div class="detail-types">
              <span 
                v-for="type in selectedPokemon.types" 
                :key="type.id"
                class="type-badge"
                :class="`type-${type.typeName}`"
              >
                {{ type.typeName }}
              </span>
            </div>
          </div>
        </div>
        <div class="detail-description">
          <p>{{ selectedPokemon.description || '暂无描述信息' }}</p>
        </div>
        <div class="detail-stats">
          <div class="stat-row">
            <span class="stat-label">身高:</span>
            <span class="stat-value">{{ selectedPokemon.height || 'N/A' }} m</span>
          </div>
          <div class="stat-row">
            <span class="stat-label">体重:</span>
            <span class="stat-value">{{ selectedPokemon.weight || 'N/A' }} kg</span>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
// 移除了所有提示
import { Search } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'
import { getPokemonList, getMockPokemonList } from '@/api/pokemon.api'

// 路由
const router = useRouter()

// 响应式数据
const loading = ref(false)
const pokemonList = ref([])
const filteredPokemonList = ref([])
const searchQuery = ref('')
const selectedType = ref('')
const selectedGeneration = ref('')
const sortBy = ref('number')
const currentPage = ref(1)
const pageSize = ref(24)
const dialogVisible = ref(false)
const selectedPokemon = ref(null)

// 宝可梦属性类型
const pokemonTypes = [
  '草', '火', '水', '电', '超能力', '冰', '龙', '恶', '妖精', 
  '格斗', '毒', '地面', '飞行', '虫', '岩石', '幽灵', '钢', '一般'
]

// 属性颜色映射
const typeColors = {
  '一般': '#A8A878',
  '火': '#F08030',
  '水': '#6890F0',
  '电': '#F8D030',
  '草': '#78C850',
  '冰': '#98D8D8',
  '格斗': '#C03028',
  '毒': '#A040A0',
  '地面': '#E0C068',
  '飞行': '#A890F0',
  '超能力': '#F85888',
  '虫': '#A8B820',
  '岩石': '#B8A038',
  '幽灵': '#705898',
  '龙': '#7038F8',
  '恶': '#705848',
  '钢': '#B8B8D0',
  '妖精': '#EE99AC'
}

// 计算属性
const totalCount = computed(() => filteredPokemonList.value.length)

const paginatedPokemonList = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredPokemonList.value.slice(start, end)
})

// 获取宝可梦数据
const fetchPokemonList = async () => {
  loading.value = true
  try {
    let response
    
    // 优先尝试从后端API获取数据
    try {
      response = await getPokemonList()
    } catch (apiError) {
      // 移除了控制台提示
      // 如果后端不可用，使用模拟数据
      response = await getMockPokemonList()
    }
    
    if (response) {
      // 处理响应数据
      const newPokemons = Array.isArray(response) ? response : (response.data || [])
      
      // 对数据按编号排序
      newPokemons.sort((a, b) => {
        const numA = parseInt(a.number || a.id || 0)
        const numB = parseInt(b.number || b.id || 0)
        return numA - numB
      })
      
      pokemonList.value = newPokemons
      filteredPokemonList.value = newPokemons
      
      console.log(`成功获取 ${newPokemons.length} 只宝可梦数据`)
      // 移除了提示
    } else {
      // 移除了控制台提示
      // 移除了提示
    }
  } catch (error) {
    // 移除了控制台提示
    // 移除了提示
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  applyFilters()
}

// 筛选处理
const handleFilter = () => {
  currentPage.value = 1
  applyFilters()
}

// 排序处理
const handleSort = () => {
  applyFilters()
}

// 应用筛选器
const applyFilters = () => {
  let filtered = [...pokemonList.value]
  
  // 搜索筛选
  if (searchQuery.value.trim()) {
    const keyword = searchQuery.value.trim().toLowerCase()
    filtered = filtered.filter(pokemon => {
      const name = getPokemonName(pokemon).toLowerCase()
      const number = getPokemonNumber(pokemon)
      const id = pokemon.id?.toString() || ''
      return name.includes(keyword) || number.includes(keyword) || id.includes(keyword)
    })
  }
  
  // 属性筛选
  if (selectedType.value) {
    filtered = filtered.filter(pokemon => {
      if (!pokemon.types || !Array.isArray(pokemon.types)) return false
      return pokemon.types.some(type => type.typeName === selectedType.value)
    })
  }
  
  // 世代筛选
  if (selectedGeneration.value) {
    const genRanges = {
      '1': [1, 151],
      '2': [152, 251],
      '3': [252, 386]
    }
    const [min, max] = genRanges[selectedGeneration.value]
    filtered = filtered.filter(pokemon => {
      const number = parseInt(pokemon.number || pokemon.id || 0)
      return number >= min && number <= max
    })
  }
  
  // 排序
  if (sortBy.value === 'number') {
    filtered.sort((a, b) => {
      const numA = parseInt(a.number || a.id || 0)
      const numB = parseInt(b.number || b.id || 0)
      return numA - numB
    })
  } else if (sortBy.value === 'name') {
    filtered.sort((a, b) => {
      const nameA = getPokemonName(a)
      const nameB = getPokemonName(b)
      return nameA.localeCompare(nameB, 'zh-CN')
    })
  }
  
  filteredPokemonList.value = filtered
}

// 重置筛选器
const resetFilters = () => {
  searchQuery.value = ''
  selectedType.value = ''
  selectedGeneration.value = ''
  sortBy.value = 'number'
  currentPage.value = 1
  filteredPokemonList.value = [...pokemonList.value]
}

// 分页处理
const handlePageChange = (page) => {
  currentPage.value = page
}

const handlePageSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
}

// 显示宝可梦详情
const showPokemonDetail = (pokemon) => {
  router.push(`/pokemon/${pokemon.id}`)
}

// 工具函数
const getPokemonImage = (pokemon) => {
  if (pokemon.imageUrl || pokemon.image_url) {
    return pokemon.imageUrl || pokemon.image_url
  }
  const id = pokemon.id || pokemon.number
  return `https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/other/official-artwork/${id}.png`
}

const getPokemonName = (pokemon) => {
  return pokemon.pokemonName || pokemon.pokemon_name || pokemon.name || '未知宝可梦'
}

const getPokemonNumber = (pokemon) => {
  return pokemon.number || pokemon.id?.toString().padStart(3, '0') || '000'
}

const handleImageError = (event, pokemon) => {
  // 图片加载失败时使用备用图片
  const id = pokemon.id || pokemon.number
  event.target.src = `https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/${id}.png`
}

// 获取宝可梦主属性颜色渐变
const getPrimaryTypeGradient = (pokemon) => {
  if (!pokemon || !pokemon.types || pokemon.types.length === 0) {
    // 默认渐变
    return 'linear-gradient(145deg, #f0f2f5, #ffffff)'
  }
  
  // 获取第一个（主）属性的颜色
  const primaryType = pokemon.types[0]
  const primaryColor = typeColors[primaryType.typeName] || '#f0f2f5'
  
  // 创建渐变效果，从属性色到白色
  return `linear-gradient(145deg, ${primaryColor}20, ${primaryColor}40, #ffffff)`
}

// 监听搜索输入，实现实时搜索
watch(searchQuery, () => {
  if (searchQuery.value.trim() === '') {
    handleSearch()
  }
})

// 组件挂载时获取数据
onMounted(() => {
  fetchPokemonList()
})
</script>

<style scoped>
.pokemon-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

/* 页面标题 */
.page-header {
  text-align: center;
  margin-bottom: 40px;
  padding: 40px 20px;
}

.page-title {
  font-size: 3.5rem;
  font-weight: bold;
  color: white;
  margin: 0 0 15px 0;
  text-shadow: 0 4px 8px rgba(0, 0, 0, 0.3);
}

.page-subtitle {
  font-size: 1.3rem;
  color: rgba(255, 255, 255, 0.9);
  margin: 0;
}

/* 搜索和筛选区域 */
.search-filter-section {
  max-width: 1200px;
  margin: 0 auto 40px auto;
  background: rgba(255, 255, 255, 0.95);
  border-radius: 20px;
  padding: 30px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
  backdrop-filter: blur(10px);
}

.search-bar {
  display: flex;
  gap: 15px;
  margin-bottom: 25px;
  align-items: center;
}

.search-bar .el-input {
  flex: 1;
  max-width: 500px;
}

.filters {
  display: flex;
  gap: 20px;
  flex-wrap: wrap;
  align-items: center;
}

.filter-group {
  display: flex;
  align-items: center;
  gap: 10px;
}

.filter-label {
  font-weight: 600;
  color: #333;
  min-width: 50px;
}

.filter-group .el-select {
  min-width: 150px;
}

/* 结果信息 */
.result-info {
  max-width: 1200px;
  margin: 0 auto 20px auto;
  display: flex;
  justify-content: space-between;
  align-items: center;
  color: white;
  font-size: 1rem;
}

.result-count strong {
  color: #FFD700;
}

/* 宝可梦网格 */
.pokemon-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 25px;
  max-width: 1200px;
  margin: 0 auto 40px auto;
  padding: 0 20px;
}

.pokemon-card {
  background: white;
  border-radius: 20px;
  padding: 20px;
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.pokemon-card:hover {
  transform: translateY(-10px);
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.2);
}

.pokemon-number {
  position: absolute;
  top: 15px;
  right: 15px;
  background: rgba(102, 126, 234, 0.1);
  color: #667eea;
  padding: 4px 8px;
  border-radius: 10px;
  font-size: 0.9rem;
  font-weight: bold;
}

.pokemon-image {
  width: 120px;
  height: 120px;
  margin: 20px auto;
  /* background: linear-gradient(145deg, #f0f2f5, #ffffff); - 移除静态背景，使用动态背景 */
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: inset 0 4px 8px rgba(0, 0, 0, 0.1);
  position: relative;
  overflow: hidden;
}

/* 精灵球背景图片 */
.pokemon-image::before {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  width: 120px;
  height: 120px;
  transform: translate(-50%, -50%);
  background: url('@/assets/bk_pokemon_img.jpg') center/contain no-repeat;
  background-size: 100% 100%;
  opacity: 0.12;
  pointer-events: none;
  z-index: 0;
  border-radius: 50%;
  transition: opacity 0.3s ease;
}

/* 悬停时精灵球背景稍微加深 */
.pokemon-card:hover .pokemon-image::before {
  opacity: 0.18;
}

.pokemon-image img {
  position: relative;
  z-index: 2;
  max-width: 100px;
  max-height: 100px;
  object-fit: contain;
  filter: drop-shadow(0 4px 8px rgba(0, 0, 0, 0.2));
}

.pokemon-info {
  text-align: center;
}

/* 宝可梦底部信息区域 */
.pokemon-bottom {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 15px;
  padding: 0 5px;
  margin-bottom: 15px;
}

.pokemon-name-section {
  flex: 1;
  text-align: left;
}

.pokemon-name {
  font-size: 1.1rem;
  font-weight: bold;
  color: #2d3748;
  margin: 0;
  line-height: 1.3;
}

/* 属性颜色块 */
.pokemon-type-colors {
  width: 24px;
  height: 40px;
  border-radius: 6px;
  overflow: hidden;
  flex-shrink: 0;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.type-color-block {
  width: 100%;
  transition: all 0.2s ease;
  cursor: pointer;
}

.type-color-block:hover {
  filter: brightness(1.1);
}

.type-badge {
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 0.8rem;
  font-weight: 600;
  color: white;
  text-transform: uppercase;
}

/* 属性类型颜色 */
.type-草 { background: #7AC74C; }
.type-火 { background: #EE8130; }
.type-水 { background: #6390F0; }
.type-电 { background: #F7D02C; color: #333; }
.type-超能力 { background: #F95587; }
.type-冰 { background: #96D9D6; }
.type-龙 { background: #6F35FC; }
.type-恶 { background: #705746; }
.type-妖精 { background: #D685AD; }
.type-格斗 { background: #C22E28; }
.type-毒 { background: #A33EA1; }
.type-地面 { background: #E2BF65; }
.type-飞行 { background: #A98FF3; }
.type-虫 { background: #A6B91A; }
.type-岩石 { background: #B6A136; }
.type-幽灵 { background: #735797; }
.type-钢 { background: #B7B7CE; }
.type-一般 { background: #A8A878; }

.pokemon-stats {
  display: flex;
  justify-content: space-around;
  margin-top: 10px;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 2px;
}

.stat-label {
  font-size: 0.8rem;
  color: #666;
}

.stat-value {
  font-size: 0.9rem;
  font-weight: bold;
  color: #333;
}

/* 空状态 */
.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: white;
}

.empty-icon {
  font-size: 4rem;
  margin-bottom: 20px;
}

.empty-state h3 {
  font-size: 1.5rem;
  margin: 0 0 10px 0;
}

.empty-state p {
  margin: 0 0 20px 0;
  opacity: 0.8;
}

/* 分页 */
.pagination-section {
  display: flex;
  justify-content: center;
  padding: 40px 20px;
}

:deep(.el-pagination) {
  --el-pagination-bg-color: rgba(255, 255, 255, 0.9);
  --el-pagination-text-color: #333;
  --el-pagination-border-radius: 10px;
}

/* 详情对话框 */
.pokemon-detail {
  padding: 20px;
}

.detail-header {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
  align-items: center;
}

.detail-image {
  width: 150px;
  height: 150px;
  background: linear-gradient(145deg, #f0f2f5, #ffffff);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: inset 0 4px 8px rgba(0, 0, 0, 0.1);
}

.detail-image img {
  max-width: 130px;
  max-height: 130px;
  object-fit: contain;
}

.detail-basic {
  flex: 1;
}

.detail-name {
  font-size: 2rem;
  font-weight: bold;
  color: #333;
  margin: 0 0 10px 0;
}

.detail-number {
  font-size: 1.2rem;
  color: #667eea;
  font-weight: bold;
  margin-bottom: 5px;
}

.detail-category {
  font-size: 1rem;
  color: #666;
  margin-bottom: 15px;
}

.detail-types {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.detail-description {
  background: #f8f9fa;
  padding: 15px;
  border-radius: 10px;
  margin-bottom: 20px;
}

.detail-description p {
  margin: 0;
  line-height: 1.6;
  color: #333;
}

.detail-stats {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.stat-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px solid #eee;
}

.stat-row:last-child {
  border-bottom: none;
}

.stat-row .stat-label {
  font-weight: 600;
  color: #333;
}

.stat-row .stat-value {
  color: #667eea;
  font-weight: bold;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-title {
    font-size: 2.5rem;
  }
  
  .search-bar {
    flex-direction: column;
  }
  
  .filters {
    flex-direction: column;
    align-items: stretch;
  }
  
  .filter-group {
    justify-content: space-between;
  }
  
  .pokemon-grid {
    grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
    gap: 20px;
  }
  
  .pokemon-bottom {
    gap: 10px;
  }
  
  .pokemon-name {
    font-size: 1rem;
  }
  
  .pokemon-type-colors {
    width: 20px;
    height: 32px;
  }
  
  /* 移动端精灵球背景调整 */
  .pokemon-image::before {
    width: 100px;
    height: 100px;
  }
  
  .pokemon-image img {
    max-width: 85px;
    max-height: 85px;
  }
  
  .result-info {
    flex-direction: column;
    gap: 10px;
    text-align: center;
  }
  
  .detail-header {
    flex-direction: column;
    text-align: center;
  }
}

.reset-primary-btn {
  color: white !important;
}

@media (max-width: 480px) {
  .pokemon-grid {
    grid-template-columns: 1fr;
    padding: 0 10px;
  }
  
  .search-filter-section {
    margin: 0 10px 20px 10px;
    padding: 20px;
  }
}
</style>